package com.x2.modular.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.x2.base.auth.annotion.Permission;
import com.x2.base.consts.ConstantsContext;
import com.x2.base.log.BussinessLog;
import com.x2.base.pojo.page.LayuiPageFactory;
import com.x2.base.pojo.page.LayuiPageInfo;
import com.x2.core.auth.util.SaltUtil;
import com.x2.core.base.controller.BaseController;
import com.x2.core.constant.dictmap.UserDict;
import com.x2.core.constant.factory.UserFactory;
import com.x2.core.exception.enums.BizExceptionEnum;
import com.x2.core.util.ToolUtil;
import com.x2.kernel.model.exception.RequestEmptyException;
import com.x2.kernel.model.exception.ServiceException;
import com.x2.kernel.model.response.ResponseData;
import com.x2.kernel.model.response.SuccessResponseData;
import com.x2.modular.system.entity.User;
import com.x2.modular.system.model.UserBean;
import com.x2.modular.system.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 系统管理员控制器
 *
 * @author x2
 * @date 2017年1月11日 下午1:08:17UserImpParam
 */
@Controller
@RequestMapping("/mgr")
public class UserMgrController extends BaseController {
    private static String PREFIX = "/system/user/";

    @Autowired
    private UserService userService;

    /**
     * 跳转到查看管理员列表的页面
     *
     * @return 页面地址
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "user.html";
    }

    /**
     * 跳转到添加页面
     *
     * @param selectDeptId:      部门id
     * @param selectDeptName：部门名
     * @param model：模型
     * @return 页面地址
     */
    @RequestMapping("/user_add")
    public String addView(String selectDeptId, String selectDeptName, Model model) {
        model.addAttribute("selectDeptId", selectDeptId);
        model.addAttribute("selectDeptName", selectDeptName);
        return PREFIX + "user_add.html";
    }


    /**
     * 跳转到编辑页面
     *
     * @param userId: 用户id
     * @return 页面地址
     */
    @Permission
    @RequestMapping("/user_edit")
    public String userEdit(@RequestParam Long userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        return PREFIX + "user_edit.html";
    }


    /**
     * 获取用户详情
     *
     * @param userId: 用户id
     * @return 结果
     */
    @RequestMapping("/getUserInfo")
    @ResponseBody
    public ResponseData getUserInfo(@RequestParam Long userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new RequestEmptyException();
        }
        return ResponseData.success(userService.getUserInfo(userId));
    }

    @RequestMapping("/getUserTree")
    @ResponseBody
    public SuccessResponseData getUserTree() {
        return new SuccessResponseData(this.userService.getSelectTreeData());
    }

    @RequestMapping("/getUserTreeAllowLogin")
    @ResponseBody
    public SuccessResponseData getUserTreeAllowLogin() {
        return new SuccessResponseData(this.userService.getSelectTreeDataAllowLogin());
    }

    /**
     * 修改当前用户的密码
     *
     * @param oldPassword:    原密码
     * @param newPassword：新密码
     * @return 结果
     */
    @RequestMapping("/changePwd")
    @ResponseBody
    public ResponseData changePwd(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword) {
        if (ToolUtil.isOneEmpty(oldPassword, newPassword)) {
            return ResponseData.error("密码为空");
        }
        return this.userService.changePwd(oldPassword, newPassword);
    }

    /**
     * 查询管理员列表
     *
     * @param userBean: 查询参数
     * @return 结果
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object list(UserBean userBean) {
        Page<UserBean> users = userService.selectUsersEx(userBean);
        return LayuiPageFactory.createPageInfo(users);
    }

    /**
     * 添加管理员
     *
     * @param user:   用户对象
     * @param result: 验证
     * @return 结果
     */
    @RequestMapping("/add")
    @BussinessLog(value = "添加管理员", key = "account", dict = UserDict.class)
    @ResponseBody
    public ResponseData add(UserBean user, BindingResult result) {
        if (result.hasErrors()) {
            return ResponseData.error(BizExceptionEnum.REQUEST_NULL.getMessage());
        }
        UserFactory.setUserPropNull(user);
        try {
            return this.userService.addUser(user);
        } catch (Exception ex) {
            return ResponseData.error(ex.getMessage());
        }
    }

    /**
     * 修改管理员
     *
     * @param user:     用户id
     * @param result：验证
     * @return 结果
     */
    @RequestMapping("/edit")
    @BussinessLog(value = "修改管理员", key = "account", dict = UserDict.class)
    @ResponseBody
    public ResponseData edit(UserBean user, BindingResult result) {
        if (result.hasErrors()) {
            return ResponseData.error(BizExceptionEnum.REQUEST_NULL.getMessage());
        }
        UserFactory.setUserPropNull(user);
        try {
            return this.userService.editUser(user);
        } catch (Exception ex) {
            return ResponseData.error(ex.getMessage());
        }
    }

    /**
     * 删除管理员
     *
     * @param userId: 用户id
     * @return 结果
     */
    @RequestMapping("/delete")
    @BussinessLog(value = "删除管理员", key = "userId", dict = UserDict.class)
    @ResponseBody
    public ResponseData delete(@RequestParam Long userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        try {
            return this.userService.deleteUser(userId);
        } catch (Exception ex) {
            return ResponseData.error(ex.getMessage());
        }
    }

    /**
     * 查看管理员详情
     *
     * @param userId: 用户id
     * @return 结果
     */
    @RequestMapping("/view/{userId}")
    @ResponseBody
    public User view(@PathVariable Long userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        return this.userService.getById(userId);
    }

    @RequestMapping(value = "{userId}")
    @ResponseBody
    public ResponseData getById(@PathVariable Long userId) {
        UserBean param = new UserBean();
        param.setUserId(userId);
        List<UserBean> userResults = this.userService.query(param);
        if (userResults != null && userResults.size() > 0) {
            return ResponseData.success(userResults.get(0));
        }
        return ResponseData.error("未获取数据");
    }

    /**
     * 重置管理员的密码
     *
     * @param userId: 用户id
     * @return 结果
     */
    @RequestMapping("/reset")
    @BussinessLog(value = "重置管理员密码", key = "userId", dict = UserDict.class)
    @ResponseBody
    public ResponseData reset(@RequestParam Long userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        User user = this.userService.getById(userId);
        user.setSalt(SaltUtil.getRandomSalt());
        user.setPassword(SaltUtil.md5Encrypt(ConstantsContext.getDefaultPassword(), user.getSalt()));
        this.userService.updateById(user);
        return SUCCESS_TIP;
    }

    /**
     * 分配角色
     *
     * @param userId:      用户id
     * @param roleIds：角色id
     * @return 结果
     */
    @RequestMapping("/setRole")
    @BussinessLog(value = "分配角色", key = "userId,roleIds", dict = UserDict.class)
    //@Permission({Const.ADMIN_NAME,Const.HR_ADMIN_NAME})
    @ResponseBody
    public ResponseData setRole(@RequestParam("userId") Long userId, @RequestParam("roleIds") String roleIds) {
        if (ToolUtil.isOneEmpty(userId, roleIds)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        this.userService.setRoles(userId, roleIds);
        return SUCCESS_TIP;
    }

    @RequestMapping("/userList")
    @ResponseBody
    public LayuiPageInfo userList(HttpServletRequest request) {
        String name = request.getParameter("name");
        Long deptId = ToolUtil.toLong(request.getParameter("deptId"), 0L);
        UserBean param = new UserBean();
        if (!ToolUtil.isEmpty(name)) {
            param.setName(name);
        }
        if (deptId.compareTo(0L) != 0) {
            param.setDeptId(deptId);
        }
        param.setStatus("ENABLE");
        return this.userService.findPageBySpec(param);
    }
}
